var express = require("express");
var router = express.Router();
var mongo = require("./db")
var mongodb = require("mongodb");
var ObjectId = mongodb.ObjectId;
// 所有关于商品的接口
// 添加 商品接口
router.post("/addProduct", function (req, res) {
  var obj = {
    img: req.body.img,
    pname: req.body.pname,
    price: req.body.price,
    des: req.body.des,
    oldprice: req.body.oldprice,
    inventory: req.body.inventory,
    oneId: req.body.oneId,
    twoId: req.body.twoId,
  }
  if (req.body.action == "add") { //添加逻辑
    obj.status = "1";//1  上架  2 下架 
    obj.isTop = "true";//是否置顶 
    mongo("insert", "productlist", obj, function () {
      res.send({ success: "添加成功" })
    })
  } else if (req.body.action == "edit") {
    mongo("update", "productlist", [{ _id: ObjectId(req.body.id) }, obj], function () {
      res.send({ success: "修改成功" })
    })
  }
})
//  查询所有商品接口
router.post("/all", function (req, res) {
  var sel = {}
  if (req.body.pname) {
    sel.pname = req.body.pname;
  }
  mongo("find", "productlist", sel, function (data) {
    res.send(data)
  })
})
// 删除接口
router.post("/delProduct", function (req, res) {
  mongo("del", "productlist", { _id: ObjectId(req.body.id) }, function () {
    res.send({ success: "删除成功" })
  })
})
// 上架和下架
router.post("/upAndDown", function (req, res) {
  mongo("update", "productlist", [{ _id: ObjectId(req.body.id) }, { status: req.body.status }], function () {
    if (req.body.status == "1") {
      res.send({ success: "上架成功" })
    } else if (req.body.status == "2") {
      res.send({ success: "下架成功" })
    }
  })
})

// 通过id查询当前编辑的数据
router.post("/findById", function (req, res) {
  mongo("find", "productlist", { _id: ObjectId(req.body.id) }, function (data) {
    res.send(data[0])
  })
})

// 通过id 查询商品详情信息
router.post("/findProduct", function (req, res) {
  mongo("find", "productlist", { _id: ObjectId(req.body.id) }, function (data) {
    res.send(data[0])
  })
})

module.exports = router;